package com.myproject.myblogserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.message.SendMessageDto;
import com.myproject.myblogserver.entity.User;
import com.myproject.myblogserver.entity.UserMessage;
import com.myproject.myblogserver.service.IUserMessageService;
import com.myproject.myblogserver.service.IUserService;
import com.myproject.myblogserver.utils.JwtUtil;

/**
 * <p>
 * 用户私信表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-16
 */
@Controller
@RequestMapping("/userMessage")
public class UserMessageController {

    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private IUserService userService;

    /**
     * 发送私信给指定用户
     */
    @PostMapping("/send/{toUserId}")
    public ResponseEntity<?> sendMessage(@PathVariable Long toUserId,
            @RequestBody SendMessageDto messageDto,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var fromUserId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 检查接收者是否存在
            var toUser = userService.lambdaQuery()
                    .eq(User::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(User::getId, toUserId)
                    .one();

            if (toUser == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("接收者不存在！");
            }

            // 创建新消息
            var message = new UserMessage();
            message.setSenderId(fromUserId);
            message.setReceiverId(toUserId);
            message.setContent(messageDto.getContent());
            userMessageService.save(message);

            return ResponseEntity.ok("发送消息成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("发送消息失败！");
        }
    }

    /**
     * 获取与指定用户的聊天记录
     */
    @GetMapping("/chat/{userId}")
    public ResponseEntity<?> getChatHistory(@PathVariable Long userId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var currentUserId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 分页获取聊天记录（包括发送和接收的消息），只查询必要字段
            var messages = userMessageService.lambdaQuery()
                    .eq(UserMessage::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .and(wrapper -> wrapper
                            .and(w -> w
                                    .eq(UserMessage::getSenderId, currentUserId)
                                    .eq(UserMessage::getReceiverId, userId))
                            .or(w -> w
                                    .eq(UserMessage::getSenderId, userId)
                                    .eq(UserMessage::getReceiverId, currentUserId)))
                    .select(UserMessage::getContent, UserMessage::getIsRead, UserMessage::getCreatedAt)
                    .orderByDesc(UserMessage::getCreatedAt)
                    .list();

            // 将当前用户作为接收者的未读消息标记为已读
            userMessageService.lambdaUpdate()
                    .set(UserMessage::getIsRead, true)
                    .eq(UserMessage::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(UserMessage::getReceiverId, currentUserId)
                    .eq(UserMessage::getSenderId, userId)
                    .eq(UserMessage::getIsRead, false)
                    .update();

            return ResponseEntity.ok(messages);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取聊天记录失败！");
        }
    }
}
